const Shape = require("./shape.js")
const Utils = require("./utils.js")
const {PLUGINS,EN} = require("./constant.js")
module.exports = class Polygon extends Shape{
	constructor($env,$event){
		super($env,$event)
		
		this.__relativePlugins=[{name:"LinePicker"},{name:PLUGINS.number,placeholder:"边框数"}]
		this.transcation = 0
		this.__setting = Utils.assign(this.__setting,{
			r:4,
			n:3
		})
		
		this.bind();
	}
	bind(){
		this.baseContext.canvas.addEventListener("click",(e)=>{
			if (!this.isActive) return;
			var pos = {
					x : e.pageX,
			        y : e.pageY
			}

			if(this.transcation===1){
				this.drawEnd(this.cvsEvtPos(pos,this.cvs));
				return;
			}
			
			this.drawStart(this.cvsEvtPos(pos,this.cvs))
		})
		this.baseContext.canvas.addEventListener("mousemove",(e)=>{
			if (!this.isActive) return;
			if(this.transcation!==1)return;
			var pos = {
					x : e.pageX,
			        y : e.pageY
			}
			this.updateBaseLine(this.cvsEvtPos(pos,this.cvs))
		})
		this.$event.on(EN.input_done,(e)=>{
			if (!this.isActive) return;
			if(e.length===0||isNaN(e)||e<3)e=this.__setting.n;
			this.__setting.n = parseInt(e);
		})
	}
	updateBaseLine(pos){
		let rect = this.__steps;
		this.clearBaseContext()
		let baseContext = this.baseContext;
		baseContext.save()
		// baseContext.globalAlpha = GHOST.alpha;
		this.rePaint([Utils.assign(rect[0],{fillStyle:this.$env.ghostFillStyle}),pos,this.__setting.n],baseContext,true)
		this.tip(this.__setting.n,rect[0],pos)
		baseContext.restore();
	}
	rePaint(step,context,fill){
		let ctx = context||this.ctx;
		
		let fp = step[0];
		let lp = step[1];

		ctx.strokeStyle = fp.strokeStyle
		ctx.fillStyle = fp.fillStyle
		ctx.setLineDash(fp.lineDash)
		
		ctx.save()
		ctx.beginPath()
		ctx.translate(fp.x,fp.y)

		let n = step[2];
		let dx = fp.x-lp.x;
		let dy = fp.y-lp.y;

		ctx.moveTo(dx,dy)
		for(let i =0;i<n;i++){
		    ctx.rotate(2*Math.PI/n)
		    ctx.lineTo(dx,dy)
		}
		ctx.closePath()
		fill&&ctx.fill();
		ctx.stroke()

		ctx.restore()
		this.drawPoint(fp,context);
	}
	drawEnd(pos){
		this.clearBaseContext()
		let step = this.__steps;
		step.push(pos);
		step.push(this.__setting.n)
		this.rePaint(step)

		this.transcation=0;

		this.emit(EN.update_state,this,step)
		this.tipHide()
	}
	drawStart(pos){

		let p = Utils.assign(this.__setting,pos);

		let ctx = this.ctx;
		p.strokeStyle = ctx.strokeStyle
		p.fillStyle = ctx.fillStyle
		p.lineDash = ctx.getLineDash()
		p=this.rewritePos(p)

		this.drawPoint(p,this.baseContext)

		this.transcation = 1;
		this.__steps=[p]
	}
	tip(n,fp,lp){
		let r = this.radius(fp,lp,this.ratio)
		this.$event.emit("tip:show",{text:`边数：${n}  半径： ${r}`})
	}
}
